package com.softwinner.awbt.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.softwinner.awbt.R;
import com.softwinner.awbt.activity.MainActivity;
import com.softwinner.awbt.common.BTApplication;
import com.softwinner.awbt.dao.Contact;
import com.softwinner.awbt.dao.ContactDao;
import com.softwinner.awbt.utils.LOG;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * Use the {@link DialFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DialFragment extends BaseFragment implements View.OnClickListener {

    private TextView mOneTextView;
    private TextView mTwoTextView;
    private TextView mThreeTextView;
    private TextView mFourTextView;
    private TextView mFiveTextView;
    private TextView mSixTextView;
    private TextView mSevenTextView;
    private TextView mEightTextView;
    private TextView mNineTextView;
    private TextView mStarTextView;
    private TextView mZeroTextView;
    private TextView mJingTextView;
    private ImageView mCallOutImageView;
    private ImageView mDelectImageView;
    private TextView mPhoneNumberTextView;
    private RecyclerView mRecyclerView;
    private ContactsAdapter mAdapter;
    private StringBuffer mStringBuffer;

    private MainActivity mActivity;
    private List<Contact> mContacts = new ArrayList<>();

    public DialFragment() {
        // Required empty public constructor
    }

    public static DialFragment newInstance() {
        return new DialFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dial, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mPhoneNumberTextView = (TextView) view.findViewById(R.id.call_number_tv);
        mPhoneNumberTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mContacts.clear();
                mContacts = BTApplication.getInstance().getDaoSession().getContactDao()
                        .queryBuilder().where(ContactDao.Properties.Number.like("%" +
                                mStringBuffer.toString().trim() + "%")).list();
                LOG.d("DialFragment--mContacts size=" + mContacts.size());
                mAdapter.setContacts(mContacts);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mZeroTextView = (TextView) view.findViewById(R.id.tv_zero);
        mOneTextView = (TextView) view.findViewById(R.id.tv_one);
        mTwoTextView = (TextView) view.findViewById(R.id.tv_two);
        mThreeTextView = (TextView) view.findViewById(R.id.tv_three);
        mFourTextView = (TextView) view.findViewById(R.id.tv_four);
        mFiveTextView = (TextView) view.findViewById(R.id.tv_five);
        mSixTextView = (TextView) view.findViewById(R.id.tv_six);
        mSevenTextView = (TextView) view.findViewById(R.id.tv_seven);
        mEightTextView = (TextView) view.findViewById(R.id.tv_eight);
        mNineTextView = (TextView) view.findViewById(R.id.tv_nine);
        mStarTextView = (TextView) view.findViewById(R.id.tv_xinghao);
        mJingTextView = (TextView) view.findViewById(R.id.tv_jinghao);
        mCallOutImageView = (ImageView) view.findViewById(R.id.call_iv);
        mDelectImageView = (ImageView) view.findViewById(R.id.delete_iv);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.contacts_lv);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mStringBuffer = new StringBuffer();
//        mStringBuffer.setLength(15);
        mZeroTextView.setOnClickListener(this);
        mOneTextView.setOnClickListener(this);
        mTwoTextView.setOnClickListener(this);
        mThreeTextView.setOnClickListener(this);
        mFourTextView.setOnClickListener(this);
        mFiveTextView.setOnClickListener(this);
        mSixTextView.setOnClickListener(this);
        mSevenTextView.setOnClickListener(this);
        mEightTextView.setOnClickListener(this);
        mNineTextView.setOnClickListener(this);
        mStarTextView.setOnClickListener(this);
        mJingTextView.setOnClickListener(this);
        mCallOutImageView.setOnClickListener(this);
        mDelectImageView.setOnClickListener(this);
        mDelectImageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                mPhoneNumberTextView.setText("");
                return true;
            }
        });
        mAdapter = new ContactsAdapter(mContacts, new ContactsFragment
                .OnListFragmentInteractionListener() {


            @Override
            public void onListFragmentInteraction(Contact item) {
                mActivity.callPhone(item.getNumber());
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            mActivity = (MainActivity) context;
        }
    }

    @Override
    public void onDetach() {
        mActivity = null;
        super.onDetach();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_one:
                inputKey("1");
                break;
            case R.id.tv_two:
                inputKey("2");
                break;
            case R.id.tv_three:
                inputKey("3");
                break;
            case R.id.tv_four:
                inputKey("4");
                break;
            case R.id.tv_five:
                inputKey("5");
                break;
            case R.id.tv_six:
                inputKey("6");
                break;
            case R.id.tv_seven:
                inputKey("7");
                break;
            case R.id.tv_eight:
                inputKey("8");
                break;
            case R.id.tv_nine:
                inputKey("9");
                break;
            case R.id.tv_xinghao:
                inputKey("*");
                break;
            case R.id.tv_zero:
                inputKey("0");
                break;
            case R.id.tv_jinghao:
                inputKey("#");
                break;
            case R.id.call_iv:
                if (BTApplication.getInstance().getStatus() == BTApplication.STATUS_CONNECTED) {
                    String phoneNumber = mPhoneNumberTextView.getText().toString().trim();
                    if (TextUtils.isEmpty(phoneNumber)) {
                        Toast.makeText(getContext(), R.string.input_number, Toast.LENGTH_SHORT)
                                .show();
                    } else if (!PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
                        Toast.makeText(getContext(), R.string.alert_input_number, Toast
                                .LENGTH_SHORT).show();
                    } else {
                        callOut(phoneNumber);
                    }
                } else if (BTApplication.getInstance().getStatus() < BTApplication
                        .STATUS_CONNECTED) {
                    Toast.makeText(getContext(), R.string.connect_phone, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), R.string.calling, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.delete_iv:
                if (mStringBuffer.length() > 0) {
                    mStringBuffer.deleteCharAt(mStringBuffer.length() - 1);
                    mPhoneNumberTextView.setText(mStringBuffer.toString());
                }

                break;
        }


    }

    private void inputKey(String key) {
//        if (mStringBuffer.length()==15) {
//            return;
//        }
        mStringBuffer.append(key);
        mPhoneNumberTextView.setText(mStringBuffer.toString());
    }

    private void callOut(String phoneNumber) {
        mActivity.callPhone(phoneNumber);
    }

}
